<?php
class ActiveForm extends CActiveForm {
        
    public $alias;
    
    public function alert($models,$htmlOptions=array()) {
        echo $this->hiddenField(is_array($models)? $models[0]:$models, 'var_');
        
        $id = Yii::app()->request->getParam('formAlias');
        if(empty($this->alias) && empty($id)){
            
        }else{
            $this->id=$this->alias;
            echo CHtml::hiddenField('formAlias', $this->id);
            if($this->id!=$id) return;
        }
        
        // display flash message
        foreach (Yii::app()->user->getFlashes() as $key => $message) {
            $htmlOptions['flashHtmlOptions']['class']=isset($htmlOptions['flashHtmlOptions']['class'])? $htmlOptions['flashHtmlOptions']['class'].$key:'flash '.$key;
            echo CHtml::openTag('div', $htmlOptions['flashHtmlOptions'])
            . $message
            . CHtml::closeTag('div');
            echo "\n";
        }//end foreach loop
        
        return $this->errorSummary($models, 
                isset($htmlOptions['header'])? $htmlOptions['header']:null, 
                isset($htmlOptions['footer'])? $htmlOptions['footer']:null,
                isset($htmlOptions['errorMessageHtmlOptions'])? $htmlOptions['errorMessageHtmlOptions']:array()
                );
    }//end function
    
    public function captchaImage(){
        $this->widget('CaptchaWidget',array(
            'template'=>'<div class="captcha">{captcha}<div class="captchaDescription">{description}</div></div>',
            'buttonLabel'=>'<br/>'.Lang::t('captcha.btn.refresh'),
            'description'=>Lang::t('captcha.description'),
        ));
    }
    
    public function editorTextArea($model,$attribute,$htmlOptions=array()){
        if(isset($htmlOptions['editorType'])){
            $type = $htmlOptions['editorType'];
        }else
            $type = in_array($model->scenario, array('adminCreate', 'adminUpdate'))? 'advance':'simple';
        
        $this->widget('ext.widgets.EEditor.EditorWidget', array('type'=>$type));
        $htmlOptions['class'] = isset($htmlOptions['class'])? 'tinymce '.$htmlOptions['class']: 'tinymce';
        return CHtml::activeTextArea($model,$attribute,$htmlOptions);
    }
    
    public function dateSelector($model,$attribute,$htmlOptions=array()){
        $this->widget('ext.widgets.juiDateTimePickerExtended.EJuiDateTimePicker', array_filter(array(
            'model' => $model,
            'attribute' => $attribute,
            'mode' => 'date',
            'options' => isset($htmlOptions['dateOptions']) ? $htmlOptions['dateOptions'] : null
        )));
    }
    
    public function singleImageUpload($model,$attribute,$htmlOptions=array()){
        if(empty($model->gallery)){
            
            if(isset($htmlOptions['imgStyle'])){
                $imgStyle=$htmlOptions['imgStyle'];
                unset($htmlOptions['imgStyle']);
            }else{
                $imgStyle='max-width:300px; max-height:200px; margin-bottom:5px; overflow:hidden;';
            }
            
            $threshold='thresholdHtmlOptions';
            if(isset($htmlOptions[$threshold])){
                $thresholdHtmlOptions=$htmlOptions[$threshold];
                unset($htmlOptions[$threshold]);
            }else{
                $thresholdHtmlOptions=array();
            }            
            if(!isset($thresholdHtmlOptions['id'])) $thresholdHtmlOptions['id']='single-img-threshold';
            if(!isset($thresholdHtmlOptions['update'])) $thresholdHtmlOptions['update']='#'.$thresholdHtmlOptions['id'];
            
            CHtml::resolveNameID($model,$attribute,$htmlOptions);
            $htmlOptions['accept']='image/*';
            
            $maxFileSize = isset(Yii::app()->params['maxImageSize'])? Yii::app()->params['maxImageSize']: 1024 * 1024 * 1;
            $this->widget('CMultiFileUpload', array(
                'model' => $model,
                'attribute' => $attribute,
                'max'=>1,
                'accept' => 'jpeg|jpg|gif|png',
                'htmlOptions'=>$htmlOptions,
                'options'=>array(
                    'onFileSelect'=>'function(e, v, m){
                        if(e.files[0].size > '.$maxFileSize.'){
                            alert("Exceeds file size limit: limit '.$maxFileSize/ (1024 * 1024).' MB.");
                            $(e).val("");
                            return false;
                        }
                    }',
                    'afterFileSelect'=>'function(e, v, m){
                        var reader = new FileReader();
                        reader.onload = function (e) {
                            $("'.$thresholdHtmlOptions['update'].'").html("<img src=\""+e.target.result+"\" style=\"'.$imgStyle.'\"  />");
                        }
                        reader.readAsDataURL(e.files[0]);
                    }',
                    'onFileRemove'=>'function(e, v, m){
                        $("'.$thresholdHtmlOptions['update'].'").html("");
                    }',
                )
            ));
            unset($thresholdHtmlOptions['update']);
            echo CHtml::openTag('div',$thresholdHtmlOptions).CHtml::closeTag('div');
            //echo CHtml::activeHiddenField($model, 'MAX_FILE_SIZE', array('value'=>$maxFileSize));
        }
        return ;
    }
    
    public function colorDropDownList($model, $attribute=null, $data=array(), $htmlOptions=array()){
        
        $options=array();
        foreach($data as $code=>$color){
            $options[$code]=array('style'=>implode('',array_filter(array(
                'background-color:'.$code.';',
                in_array($code, array(
                    Option::COLOR_BLACK,
                    Option::COLOR_MAROON,
                    Option::COLOR_GREEN,
                    Option::COLOR_BLUE,
                    Option::COLOR_NAVY,
                    Option::COLOR_PURPLE,
                ))? 'color:white;':'',
            ))));
        }
        if(!empty($options)) $htmlOptions['options']=$options;
        return CHtml::activeDropDownList($model, $attribute, $data, $htmlOptions);
    }
    
    public function avatarUpload($model,$attribute,$htmlOptions=array()){
        if(!isset($htmlOptions['template'])) $htmlOptions['template']='{image}<br />{remove}';
        if(empty($model->photo)){
            if($model->isSocialUser)
                return CHtml::image($model->avatar, $model->username);
            return $this->singleImageUpload($model,$attribute,$htmlOptions);
        }else{
            if(!isset($htmlOptions['imageOptions'])) $htmlOptions['imageOptions']=array();
            return strtr($htmlOptions['template'], array(
                '{image}'=>CHtml::image($model->thumbnail, $model->title, $htmlOptions['imageOptions']),
                '{remove}'=>CHtml::link('Remove photo', Yii::app()->createUrl('ajax/deleteimage', array('id'=>$model->id, 'module'=>strtolower(get_class($model)), 'imageId'=>$model->photo->id))),
            ));
        }
    }
    
    public function logoUpload($model,$attribute,$htmlOptions=array()){
        if(!isset($htmlOptions['template'])) $htmlOptions['template']='{image}<br />{remove}';
        if(empty($model->photo)){
            return $this->singleImageUpload($model,$attribute,$htmlOptions=array());
        }else{
            if(!isset($htmlOptions['imageOptions'])) $htmlOptions['imageOptions']=array();
            return strtr($htmlOptions['template'], array(
                '{image}'=>CHtml::image($model->thumbnail, $model->title, $htmlOptions['imageOptions']),
                '{remove}'=>CHtml::link('Remove photo', Yii::app()->createUrl('ajax/deleteimage', array('id'=>$model->id, 'module'=>strtolower(get_class($model)), 'imageId'=>$model->photo->id))),
            ));
        }
    }
    
    public function multiImageUpload($model,$attribute,$htmlOptions=array()){
        CHtml::resolveNameID($model,$attribute,$htmlOptions);
        
        if(isset($htmlOptions['listTemplate'])){
            $listTemplate=$htmlOptions['listTemplate'];
            unset($htmlOptions['listTemplate']);
        }else{
            $listTemplate='{img}';
        }
        
        if(isset($htmlOptions['imgStyle'])){
            $imgStyle=$htmlOptions['imgStyle'];
            unset($htmlOptions['imgStyle']);
        }else{
            $imgStyle='max-width:300px; max-height:200px; margin-bottom:5px; overflow:hidden;';
        }
        
        $threshold='thresholdHtmlOptions';
        if(isset($htmlOptions[$threshold])){
            $thresholdHtmlOptions=$htmlOptions[$threshold];
            unset($htmlOptions[$threshold]);
        }else{
            $thresholdHtmlOptions=array();
        }            
        if(!isset($thresholdHtmlOptions['id'])) $thresholdHtmlOptions['id']='multiple-img-threshold';
        if(!isset($thresholdHtmlOptions['update'])) $thresholdHtmlOptions['update']='#'.$thresholdHtmlOptions['id'];
        
        $htmlOptions['accept']='image/*';
        $maxFileSize = isset(Yii::app()->params['maxImageSize'])? Yii::app()->params['maxImageSize']: 1024 * 1024 * 1;
        $this->widget('CMultiFileUpload', array(
            'model' => $model,
            'attribute' => $attribute,
            'accept' => 'jpeg|jpg|gif|png',
            'htmlOptions'=>$htmlOptions,
            'options'=>array(
                'list'=>$thresholdHtmlOptions['update'],
                'onFileSelect'=>'function(e, v, m){
                    if(e.files[0].size > '.$maxFileSize.'){
                        alert("Exceeds file size limit: limit '.$maxFileSize/ (1024 * 1024).' MB.");
                        $(e).val("");
                        return false;
                    }
                }',
                'afterFileSelect'=>'function(e, v, m){
                    var id=v;
                    id=id.replace(/\\\/gi,"").replace(".","").replace("C:","");

                    var reader = new FileReader();
                    reader.onload = function (e) {
                       $("'.$thresholdHtmlOptions['update'].'").append("'.strtr($listTemplate, array(
                           '{img}'=>'<img id=\""+id+"\" src=\""+e.target.result+"\" style=\"'.$imgStyle.'\" />',
                       )).'");
                    }
                    reader.readAsDataURL(e.files[0]);
                }',
                'afterFileRemove'=>'function(e, v, m){
                    var id=v;
                    id=id.replace(/\\\/gi,"").replace(".","").replace("C:","");
                    $("img#"+id).remove();                    
                }',
            )
        ));
        echo CHtml::openTag('div', $thresholdHtmlOptions).CHtml::closeTag('div');
        return ;
    }
    
    public function multiFileUpload($model,$attribute,$htmlOptions=array()){
        //$htmlOptions['accept']='image/*';
        $maxFileSize = isset(Yii::app()->params['maxFileSize'])? Yii::app()->params['maxFileSize']: 1024 * 1024 * 1;
        $this->widget('CMultiFileUpload', array(
            'model' => $model,
            'attribute' => $attribute,
            'accept' => 'pdf|rar|doc|docx|wps|torrent|zip|txt|ttf|rtf|pps|ppt|jpeg|jpg|gif|png',
            'htmlOptions'=>$htmlOptions,
            'options'=>array(
                'onFileSelect'=>'function(e, v, m){
                    if(e.files[0].size > '.$maxFileSize.'){
                        alert("Exceeds file size limit: limit '.$maxFileSize / (1024 * 1024).' MB.");
                        $(e).val("");
                        return false;
                    }
                }'
            )
        ));
        return ;
    }
    
    public static function getFormInstance(&$form, $attribute, $default=null){
        return isset($form[$attribute])? $form[$attribute]: $default;
    }
    
    public function galleryEditor($model,$attribute,$htmlOptions=array()){
        if(empty($model->gallery)) return ;
        
        $template=isset($htmlOptions['template'])? $htmlOptions['template']:'<li>{image}</li>';
        $separator = isset($htmlOptions['separator'])? $htmlOptions['separator']:'<br />';
        //'{image}{captionInput}{control}{id}{fileName}{type}{size}{totalView}{creator}{editor}'
        $imageTemplate = isset($htmlOptions['imageTemplate'])? $htmlOptions['imageTemplate']:implode($separator, array(
          '{image}',
          '{id} | {fileName}',
          '{captionInput} | {control}',
          '{type} | {size} | {totalView}',
          '',
          //'{creator}',
          //'{editor}',
        ));
        $imageOptions = isset($htmlOptions['imageOptions'])? $htmlOptions['imageOptions']:array();
        $captionOptions=isset($htmlOptions['captionOptions'])? $htmlOptions['captionOptions']:array();

        unset($htmlOptions['template'],$htmlOptions['imageTemplate'],$htmlOptions['imageOptions'],$htmlOptions['captionOptions']);
        
        if(!isset($htmlOptions['id'])) $htmlOptions['id']='gallery-editor';
        
        $this->widget('ext.widgets.EPrettyPhoto.PrettyPhotoWidget',array(
            'selector'=> 'a[rel=\'prettyPhoto['.$htmlOptions['id'].']\']',
            'options'=>array(
                'animation_speed'=>'fast',
                'slideshow'=>3000,
                'theme'=>'dark_rounded',
                'social_tools'=>'',
            )
        ));
        
        echo CHtml::openTag('ul', $htmlOptions);
        foreach($model->gallery as $id=>$image):
            $captionOptions['value']=$image->fileCaption;
            
            echo strtr($template, array(
                '{image}' => strtr($imageTemplate, array(
                    '{image}' => CHtml::link(CHtml::image($image->largeSquareThumbnail, $image->fileCaption, $imageOptions), $image->originalFile, array(
                        'title'=>$image->fileCaption,
                        'rel'=>"prettyPhoto[".$htmlOptions['id']."]",
                    )),
                    '{id}' => Lang::t('gallery.editor.lbl.image.id', array('{imageId}' => $image->id)),
                    '{fileName}' => Lang::t('gallery.editor.lbl.file.name', array('{fileName}' => $image->fileName)),
                    '{type}' => Lang::t('gallery.editor.lbl.file.type', array('{type}' => $image->fileType)),
                    '{size}' => Lang::t('gallery.editor.lbl.file.size', array('{size}' => (int) ($image->fileSize / 1024))),
                    '{totalView}' => Lang::t('gallery.editor.lbl.total.view', array('{total}' => $image->totalView)),
                    '{creator}' => Lang::t('gallery.editor.lbl.creator', array('{date}' => date('j-M-Y h:i:s', $image->createdTime), '{username}' => $image->creatorName)),
                    '{editor}' => Lang::t('gallery.editor.lbl.modifier', array('{date}' => date('j-M-Y h:i:s', $image->updatedTime), '{username}' => $image->editorName)),
                    '{control}' => implode(' | ', array(
                        $image->isDefault ? Lang::t('gallery.editor.lbl.default') : CHtml::link(Lang::t('gallery.editor.lbl.make.default'), Yii::app()->createUrl('ajax/defaultimage', array('id' => $model->id,'module'=>strtolower(get_class($model)), 'imageId' => $image->id))),
                        CHtml::link(Lang::t('gallery.editor.lbl.delete'), Yii::app()->createUrl('ajax/deleteimage', array('id' => $model->id,'module'=>strtolower(get_class($model)), 'imageId' => $image->id))),
                    )),
                    '{captionInput}' => Lang::t('gallery.editor.lbl.caption') . ' ' . CHtml::activeTextField($model, 'imageEditor_[' . $image->id . ']', $captionOptions),
                ))
            ));
        endforeach;
        echo CHtml::closeTag('ul');
    }
    
    public static function getVideoInstance($model, $attribute){        
        $video=Yii::app()->request->getParam(get_class($model), array());
        if(empty($video) || !isset($video[$attribute])) return array();
        
        $result=array();
        foreach(array_keys($video[$attribute]) as $param){
            foreach(array_values($video[$attribute][$param]) as $id=>$value){
                $result[$id][$param]=$value;
            }
        }
        return $result;
    }
    
    public function videoUpload($model,$attribute,$htmlOptions=array()){
        
        $limit=self::getFormInstance($htmlOptions, 'limit', 0);
        
        if(!empty($model->channel)){
            $total = count($model->channel);
            if($total >= $limit)
                return ;
            else
                $limit -= $total;
        }
        
        $editorCssClass=self::getFormInstance($htmlOptions, 'editorCssClass', 'video-editor');
        $inputCssClass=self::getFormInstance($htmlOptions, 'inputCssClass');
        $inputMaxLength=self::getFormInstance($htmlOptions, 'inputMaxLength', 100);
        $inputSeparator=self::getFormInstance($htmlOptions, 'inputSeparator', ' | ');        
        
        $template=self::getFormInstance($htmlOptions, 'template', 
                CHtml::openTag('p', array('class'=>implode(' ', array_filter(array('video-url',$inputCssClass)))))
                .'{url}{caption}'
                .CHtml::closeTag('p')
                );
        
        echo CHtml::openTag('div', array('class'=>$editorCssClass));        
            if(empty($model->$attribute)){
                echo strtr($template, array(
                    '{url}'=>Lang::t('video.editor.lbl.url').' '.CHtml::activeTextField($model, $attribute.'[url][]', array('class'=>'caption','value'=>'','maxLength'=>$inputMaxLength)),
                    '{caption}'=>Lang::t('video.editor.lbl.caption').' '.CHtml::activeTextField($model, $attribute.'[caption][]', array('class'=>'caption','value'=>'','maxLength'=>$inputMaxLength)),
                ));                
            }else{
                foreach($model->$attribute as $key=>$value){
                    echo strtr($template, array(
                        '{url}'=>Lang::t('video.editor.lbl.url').' '.CHtml::activeTextField($model, $attribute.'[url][]', array('class'=>'caption','value'=>$value['url'],'maxLength'=>$inputMaxLength)),
                        '{caption}'=>Lang::t('video.editor.lbl.caption').' '.CHtml::activeTextField($model, $attribute.'[caption][]', array('class'=>'caption','value'=>$value['caption'],'maxLength'=>$inputMaxLength)),
                    ));
                    
                }
            }
            $this->widget('ext.widgets.reCopy.ReCopyWidget', array('targetClass'=>'video-url', 'limit'=>$limit));
            
        echo CHtml::closeTag('div');
        return ;
    }
    
    public function videoEditor($model,$attribute,$htmlOptions=array()){
        if(empty($model->channel)) return ;
        
        $editorCssClass=self::getFormInstance($htmlOptions, 'editorCssClass', 'video-editor');
        $inputCssClass=self::getFormInstance($htmlOptions, 'inputCssClass');
        $inputMaxLength=self::getFormInstance($htmlOptions, 'inputMaxLength', 100);
        $inputSeparator=self::getFormInstance($htmlOptions, 'inputSeparator', '<br />');
        $videoHtmlOptions=self::getFormInstance($htmlOptions, 'videoHtmlOptions', array());
        
        echo CHtml::openTag('div', array('class'=>$editorCssClass));
        foreach($model->channel as $id=>$video){
            echo CHtml::openTag('div', array('class'=>'row'));
            
            $video->defaultWidth=self::getFormInstance($videoHtmlOptions, 'width', 250);
            $video->defaultHeight=self::getFormInstance($videoHtmlOptions, 'height', 250);
            $video->defaultImage=self::getFormInstance($videoHtmlOptions, 'defaultImage');
            $showThumbnail=self::getFormInstance($videoHtmlOptions, 'showThumbnail', false);
            
            echo '<div class="video">';
            echo $showThumbnail || !$video->hasHtml? 
                    CHtml::image($video->thumbnail, $video->title, array('width'=>$video->defaultWidth, 'height'=>$video->defaultHeight))
                    : $video->embedHtml;
            echo '</div>';
            
            echo '<div class="fields">'.implode('', array_filter(array(
                '<span class="row"><label>'.Lang::t('video.editor.lbl.video.id').'</label>'.$video->id.'</span>',
                '<span class="row"><label>'.Lang::t('video.editor.lbl.url').'</label>'.CHtml::activeTextField($model, $attribute.'['.$video->id.'][url]', array('class'=>'url','value'=>$video->fileUrl,'maxLength'=>$inputMaxLength)).'</span>',
                '<span class="row"><label>'.Lang::t('video.editor.lbl.caption').'</label>'.CHtml::activeTextField($model, $attribute.'['.$video->id.'][caption]', array('class'=>'caption','value'=>$video->fileCaption,'maxLength'=>$inputMaxLength)).'</span>',
                '<span class="row links">',
                implode(' | ', array_filter(array(
                    $video->isDefault? Lang::t('video.editor.lbl.default'): CHtml::link(Lang::t('video.editor.lbl.make.default'), Yii::app()->createUrl('ajax/defaultvideo', array('id'=>$model->id,'module'=>strtolower(get_class($model)), 'videoId'=>$video->id))),
                    CHtml::link(Lang::t('video.editor.lbl.delete'), Yii::app()->createUrl('ajax/deletevideo', array('id'=>$model->id,'module'=>strtolower(get_class($model)), 'videoId'=>$video->id))),
                ))),
                '</span>',
            ))).'</div>';            
            echo CHtml::closeTag('div');//end row
        }//end foreach
        echo CHtml::closeTag('div');
    }
    
    public function urlExtractTextField($model,$attribute,$htmlOptions=array()){
        CHtml::resolveNameID($model,$attribute,$htmlOptions);
        $htmlOptions['embedOptions']['selector']='#'.$htmlOptions['id'];
        $this->widget('ext.widgets.oembed.COEmbedWidget', $htmlOptions['embedOptions']);
        return $this->textField($model,$attribute,$htmlOptions=array());
    }
    
    public function counterTextArea($model,$attribute,$htmlOptions=array()){
        CHtml::resolveNameID($model,$attribute,$htmlOptions);
        $htmlOptions['counterOptions']['selector'] = '#'.$htmlOptions['id'];
        if(isset($htmlOptions['maxlength'])) $htmlOptions['counterOptions']['max']=$htmlOptions['maxlength'];
        $this->widget('ext.widgets.ECharCounter.ECharCounterWidget', $htmlOptions['counterOptions']);
        unset($htmlOptions['counterOptions']);
        return $this->textArea($model,$attribute,$htmlOptions);
    }
    
}//end class